//
//  CZItemCell.m
//  A01-CZ彩票
//
//  Created by apple on 15-6-16.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "CZItemCell.h"
#import "CZItem.h"
#import "CZItemArrow.h"
#import "CZItemSwitch.h"
#import "CZItemLabel.h"

@interface CZItemCell ()

@property (nonatomic, strong) UIImageView *iconView;
@property (nonatomic, strong) UISwitch *switchView;
@property (nonatomic, strong) UILabel *timeView;
@end

@implementation CZItemCell
//1 创建一个可重用的自定义cell
+ (instancetype)cellWithTableView:(UITableView *)tableView{

    return [self cellWithTableView:tableView style:UITableViewCellStyleDefault];
}

+ (instancetype)cellWithTableView:(UITableView *)tableView style:(UITableViewCellStyle)style{
    static NSString *reuseId = @"item";
    CZItemCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[self alloc] initWithStyle:style reuseIdentifier:reuseId];
    }
    return cell;
}


//懒加载
- (UIImageView *)iconView{
    if (_iconView == nil) {
        _iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CellArrow"]];
    }
    return _iconView;
}

- (UISwitch *)switchView{
    if (_switchView == nil) {
        _switchView = [UISwitch new];
        //加载开关的状态
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [_switchView setOn:[userDefaults boolForKey:self.item.title]];
        
        [_switchView addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    }
    return _switchView;
}

//点击开关，存储开关的状态
- (void)valueChange:(UISwitch *)sender{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:sender.isOn forKey:self.item.title];
    [userDefaults synchronize];
}

- (UILabel *)timeView{
    if (_timeView == nil) {
        _timeView = [UILabel new];
        _timeView.textColor = [UIColor grayColor];
    }
    return _timeView;
}

//2
- (void)setItem:(CZItem *)item{
    _item = item;
    self.textLabel.text = item.title;
    if (item.icon) {
        self.imageView.image = [UIImage imageNamed:item.icon];
    }
    
    //设置子标题
    if (item.subTitle) {
        self.detailTextLabel.text= item.subTitle;
    }
    
    //判断当前的模型是箭头还是开关  还是label
    if ([item isKindOfClass:[CZItemArrow class]]) {
        //设置箭头
        //        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        self.accessoryView = self.iconView;
    }else if([item isKindOfClass:[CZItemSwitch class]]){
        //不允许cell选中
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.accessoryView = self.switchView;
    }else if([item isKindOfClass:[CZItemLabel class]]){
        //显示时间  label
        
        self.timeView.text = item.time;
        [self.timeView sizeToFit];  //设置label的大小和内容的大小一致
        self.accessoryView = self.timeView;
    }else{
        
        self.accessoryView = nil;
    }

}
@end
